import re

from django.contrib.auth.backends import ModelBackend
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response

from users.models import User


def jwt_response_payload_handler(token, user=None, request=None):
    return {
        'token': token,
        'id': user.id,
        'username': user.username
    }


class UsernameAuthentication(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        if request is None:
            try:
                user = User.objects.get(username=username, is_staff=True)
            except:
                return None
            if user.check_password(password):
                return user

        else:
            # user = get_user_by_account(username)

            if re.match(r'1[3-9]\d{9}$', username):
                user = User.objects.get(mobile=username)
            else:
                user = User.objects.get(username=username)

            if user and user.check_password(password):
                return user


class PageNum(PageNumberPagination):

    page_size = 5
    page_size_query_param = 'pagesize'
    max_page_size = 10

    def get_paginated_response(self, data):
        return Response({
            'count': self.page.paginator.count,
            'lists': data,
            'page': self.page.number,
            'pages': self.page.paginator.num_pages,
            'pagesize': self.page_size
        })
